#include "public.h"
#include <QtGui>
#include "AlphaBaseWidget.h"


AlphaBaseWidget::AlphaBaseWidget( QWidget* wgtParent)
: QWidget(wgtParent)
{
	setWindowFlags(Qt::FramelessWindowHint | Qt::Widget);
	setWindowTitle("AlphaWidget");
	m_WidgetMask = QPixmap(":forms/AlphaBg.png");
	m_Alpha = 255;
	setMouseTracking(true);

	SetWindowLong(winId(), 
		GWL_EXSTYLE, 
		GetWindowLong(winId(), GWL_EXSTYLE) | WS_EX_LAYERED);
}

void AlphaBaseWidget::resizeEvent(QResizeEvent *e)
{
	m_WidgetMask = m_WidgetMask.scaled(width(), height());
}

void AlphaBaseWidget::setLayered()
{
	SetWindowLong(winId(), 
		GWL_EXSTYLE, 
		GetWindowLong(winId(), GWL_EXSTYLE) | WS_EX_LAYERED); //make shure the QAlphaWidget is realy a windows QAlphaWidget form
}

void AlphaBaseWidget::updateAlpha(QPixmap &pixmap)
{
	HBITMAP oldBitmap;
	HBITMAP hBitmap;	
	SIZE size;
	size.cx = pixmap.width();
	size.cy = pixmap.height();
	HDC screenDc = GetDC(NULL);
	POINT pointSource;
	pointSource.x = 0;
	pointSource.y = 0; 
	POINT topPos;
	topPos.x = x();
	topPos.y = y();	
	HDC memDc = CreateCompatibleDC(screenDc);
	BLENDFUNCTION blend;
	blend.BlendOp             = AC_SRC_OVER;
	blend.BlendFlags          = 0;
	blend.SourceConstantAlpha = m_Alpha;
	blend.AlphaFormat         = AC_SRC_ALPHA;
	hBitmap = pixmap.toWinHBITMAP(QPixmap::PremultipliedAlpha); 
	oldBitmap = (HBITMAP)SelectObject(memDc, hBitmap);

	UpdateLayeredWindow(winId(), screenDc,  &topPos,  &size, memDc,  &pointSource, 0, &blend, ULW_ALPHA);


	ReleaseDC( NULL, screenDc);
	if (hBitmap != NULL)
	{
		SelectObject(memDc, oldBitmap);
		DeleteObject(hBitmap); 
		DeleteObject(hBitmap);
	}
	DeleteDC(memDc); 
}

void AlphaBaseWidget::paintEvent(QPaintEvent *event)
{
	QPainter p(&m_WidgetMask);
	QObjectList ol = children();
	foreach(QObject *o, ol)
	{
		if(o->isWidgetType())
		{
			QWidget* child = dynamic_cast<QWidget*>(o);  

			p.drawPixmap(child->geometry(),drawCtrl(child ));
		}

	}
	p.end();

	updateAlpha(m_WidgetMask);

}

QPixmap AlphaBaseWidget::drawCtrl(QWidget * widget)
{
	if (!widget)
		return QPixmap();
	QRect r(widget->rect());
	QPixmap res(r.size());
	widget->render(&res, -r.topLeft(), r, QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);

	return res;

} 
